package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.behavior.entity.ApLikesBehavior;
import com.usian.behavior.mapper.ApLikesBehaviorMapper;
import com.usian.behavior.service.IApLikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.common.util.JsonUtils;
import com.usian.model.article.msg.ArticleBehaviorMsg;
import com.usian.model.behavior.dtos.LikesBehaviorDto;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.usian.common.constants.message.HotArticleConstants.HOT_ARTICLE_SCORE_STREAM_TOPIC;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-18
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements IApLikesBehaviorService {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public void like(LikesBehaviorDto dto) {
        //1、参数校验
        if (dto == null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2、获取用户id，判断用户是否登录
        boolean isUser = false;
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId != null && userId != 0) {
            //用户是登录状态
            isUser = true;
        }

        if (userId == null && dto.getEquipmentId() == null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE, "用户id和设备id不能同时为空");
        }

        //3、查询用户或设备针对当前文章是否已经点赞
        QueryWrapper<ApLikesBehavior> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApLikesBehavior::getArticleId, dto.getArticleId());
        if (isUser) {
            //登录状态，根据用户id查询
            queryWrapper.lambda().eq(ApLikesBehavior::getApUserId, userId);
        } else {
            //未登录状态，根据设备号查询
            queryWrapper.lambda().eq(ApLikesBehavior::getEquipmentId, dto.getEquipmentId());
        }

        ApLikesBehavior likesBehavior = this.getOne(queryWrapper);
        if (likesBehavior == null) {
            //3.1 如果未点赞，记录点赞行为
            likesBehavior = new ApLikesBehavior();
            if (isUser) {
                likesBehavior.setApUserId(userId);
            } else {
                likesBehavior.setEquipmentId(dto.getEquipmentId());
            }
            likesBehavior.setArticleId(dto.getArticleId());
            likesBehavior.setOperation(dto.getOperation());
            likesBehavior.setType(dto.getType());
            likesBehavior.setCreatedTime(new Date());
            likesBehavior.setUpdateTime(new Date());
            boolean b = this.save(likesBehavior);
        } else {
            //3.2 如果已经点赞，更新点赞状态
            likesBehavior.setOperation(dto.getOperation());
            likesBehavior.setUpdateTime(new Date());
            updateById(likesBehavior);
        }
        //如果是点赞行为，生成点赞行为实时流处理消息
        if (dto.getOperation() == 1) {
            ArticleBehaviorMsg articleBehaviorMsg = new ArticleBehaviorMsg(dto.getArticleId(),1,ArticleBehaviorMsg.ArticleBehaviorType.LIKES);
            kafkaTemplate.send(HOT_ARTICLE_SCORE_STREAM_TOPIC, JsonUtils.toString(articleBehaviorMsg));
        }

    }

    @Override
    public ApLikesBehavior findLikeByArticleId(Integer userId, String equipmentId, Long articleId, Integer type) {
        //查询用户或者设备号查询点赞行为
        boolean isUser = false;
        if (userId != null && userId != 0) {
            isUser = true;
        }
        //查询用户或者设备是否对当前文章进行点赞
        QueryWrapper<ApLikesBehavior> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApLikesBehavior::getArticleId, articleId).eq(ApLikesBehavior::getType, type);
        if (isUser) {
            queryWrapper.lambda().eq(ApLikesBehavior::getApUserId, userId);
        } else {
            queryWrapper.lambda().eq(ApLikesBehavior::getEquipmentId, equipmentId);
        }
        ApLikesBehavior likesBehavior = this.getOne(queryWrapper);

        return likesBehavior;
    }

}
